package server_commands;

import static server.RLM_Server.activeConnections;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;

import connection_modul.DatabaseConnection;
import server.ServerSocketConnection;

public class LOGOUTCommand extends Command {

	
	public LOGOUTCommand(String parameter) {
		setCode(LOGOUT_CMD);
		setParameter(parameter);
	}
	
	/**
	 * Metoda menja status odgovarajuceg korisnika u offline i obavestava sve korisnike,
	 * na cijoj je listi dati korisnik, o loggout statusu. 
	 *
	 * @param connection - konekcija ka klijentu
	 * @param dbConnection - objekat za rad sa bazom
	 * 
	 * @notice Konekcija sa klijentom se ne prekida pozivom ove metode.
	 * 
	 * @author Uros Krkic & Martin Jondzic
	 * 
	 */
	public boolean executeCommand(ServerSocketConnection connection, DatabaseConnection dbConnection) {

		String username = getParameter();
		
		// Promena statusa korisnika u bazi
		String logoutSQLCommand = "UPDATE tblUsers SET tblUsers.status='Offline'" +
								  " WHERE tblUsers.username='" + username + "'";
		
		try {
			dbConnection.doUpdateStatement(logoutSQLCommand);
			
//			connection.setMessage("100 Logout OK");
			
			// Selektuje sve korisnike koji imaju na listi aktuelnog korisnika, a nisu
			// blokirani na korisnikovoj listi.			

			String SQLSelectQuery = "SELECT tblContacts.user_dest " +
			"FROM tblContacts " +
			"WHERE  tblContacts.user_source = '" + username + "' AND tblContacts.user_dest NOT IN " +
			"(SELECT tblBlocks.user_dest FROM tblBlocks WHERE tblBlocks.user_source = '" + username + "');";
			
			dbConnection.doStatement(SQLSelectQuery);
			
			// dobavljeni su nikovi korisnika koje treba obavestiti o statusu
			// korisnika		
		
			ArrayList array = (ArrayList)dbConnection.data.clone();
		
			if(array.size() == 0) {
				dbConnection.doCommit();
				return true;
			}
			
			String message = "SERV_LOGOUT " + username;
		
			// Obavestava sve korisnike o logout-u datog korisnika

			Iterator usersIterator = array.iterator();
		
			while ( usersIterator.hasNext() ) {
			
				// username korisnika 
				String user = ((Vector)usersIterator.next()).get(0).toString();
			
				ServerSocketConnection tempConnection = activeConnections.get(user);
			
				if (tempConnection != null) {
					tempConnection.setMessage(message);
//					System.out.println("Korisnik koji se obavestava o delogovanju novog usera: " + user);
				}
			}
		
			System.out.println("--> User " + username + " has just logged out!");
		
		} catch (SQLException e) {
			e.printStackTrace();
			dbConnection.doRollBack();
			return false;
		}	
		
		dbConnection.doCommit();
		
		return true;
	}
	
}
